<?php

namespace App\Controllers\Admin;

use App\Controllers\AdminBase;
use App\Models\PiecesModel;

class Pieces extends AdminBase
{

    protected $piecesModel;
    public $type;

    public function __construct(...$param)
    {
        $this->piecesModel = new PiecesModel();
        $this->type = ['input' => '单行文本', 'textarea' => '多行文本', 'editor' => '编辑器', 'file' => '单文件', 'files' => '多文件', 'media' => '音视频', 'keyvalue' => '键值对'];
    }

    /**
     *  碎片内容列表
     */
    public function index()
    {
        if (IS_POST) {
            $page = $this->request->getPost('page');
            $limit = $this->request->getPost('limit');
            $param = $this->request->getPost();

            list($list, $total, $param) = $this->piecesModel->limit_page($page, $limit, 0, $param);
            $return = [
                'total' => $total,
                'data' => $list,
            ];
            $this->_json(0, 'ok', $return);
        }
        $vdata = [
            'type' => $this->type,
        ];
        return view('pieces/index.html', $vdata);
    }

    /**
     * 发布碎片内容
     */
    public function add()
    {
        if (IS_POST) {
            $data = $this->request->getPost('data');
            $rt = $this->piecesModel->add($data);
            if ($rt['code'] == 0) {
                $this->addSystemLog('添加自定义碎片内容: ' . $data['title']);
            }
            $this->_json($rt);
        }
        $vdata = [
            'type' => $this->type,
        ];
        return view('pieces/add.html', $vdata);
    }

    /**
     * 修改碎片内容
     */
    public function edit()
    {
        $id = intval($this->request->getGet('id'));
        if (IS_POST) {
            $data = $this->request->getPost('data');
            $rt = $this->piecesModel->edit($id, $data);
            if ($rt['code'] == 0) {
                $this->addSystemLog('修改产品: ' . $data['title']);
            }
            $this->_json($rt);
        }
        $row = $this->piecesModel->get($id);

        $vdata = [
            'type' => $this->type,
            'data' => $row,
        ];
        return view('pieces/add.html', $vdata);
    }

    /**
     * 删除碎片内容
     */
    public function del()
    {
        $yes = $no = 0;
        if (IS_POST) {
            $ids = $this->request->getPost('ids');
            if ($ids && is_array($ids)) {
                foreach ($ids as $id) {
                    $rt = $this->piecesModel->del($id);
                    if ($rt['code'] == 0) {
                        $this->addSystemLog('删除产品:#' . $id);
                        $yes++;
                    } else {
                        $no++;
                    }
                }
            } else {
                $this->_json(1, '碎片内容错误');
            }
            $this->_json(0, '操作结果 成功：' . $yes . ',失败' . $no);
        }
        $this->_json(1, isset($rt['msg']) ? $rt['msg'] : '操作失败');
    }


}
